package vote.ai.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import vote.util.SmartRequestUtil;

import java.time.LocalDateTime;

/**
 * Mybatis Plus 插入或者更新时指定字段设置值
 *
 * @author zhoumingfa
 */
@Component
@Slf4j
public class MybatisPlusFillHandler implements MetaObjectHandler {

    public static final String CREATE_TIME = "createTime";

    public static final String CREATED_AT = "createdAt";

    public static final String UPDATE_TIME = "updateTime";

    public static final String UPDATED_AT = "updatedAt";

    public static final String CREATED_BY = "createdBy";

    public static final String UPDATED_BY = "updatedBy";

    @Override
    public void insertFill(MetaObject metaObject) {
        // 填充创建时间
        if (metaObject.hasSetter(CREATE_TIME)) {
            this.setFieldValByName(CREATE_TIME, LocalDateTime.now(), metaObject);
        }
        if (metaObject.hasSetter(UPDATE_TIME)) {
            this.setFieldValByName(UPDATE_TIME, LocalDateTime.now(), metaObject);
        }

        // 填充创建时间
        if (metaObject.hasSetter(CREATED_AT)) {
            this.setFieldValByName(CREATED_AT, LocalDateTime.now(), metaObject);
        }
        if (metaObject.hasSetter(UPDATED_AT)) {
            this.setFieldValByName(UPDATED_AT, LocalDateTime.now(), metaObject);
        }

        // 填充创建者
        if (metaObject.hasSetter(CREATED_BY)) {
            log.info("createdBy:{}", SmartRequestUtil.getRequestUserId());
            this.setFieldValByName(CREATED_BY, SmartRequestUtil.getRequestUserId(), metaObject);
        }
        if (metaObject.hasSetter(UPDATED_BY)) {
            this.setFieldValByName(UPDATED_BY, SmartRequestUtil.getRequestUserId(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasSetter(UPDATE_TIME)) {
            this.setFieldValByName(UPDATE_TIME, LocalDateTime.now(), metaObject);
        }

        if (metaObject.hasSetter(UPDATED_AT)) {
            this.setFieldValByName(UPDATED_AT, LocalDateTime.now(), metaObject);
        }

        if (metaObject.hasSetter(UPDATED_BY)) {
            this.setFieldValByName(UPDATED_BY, SmartRequestUtil.getRequestUserId(), metaObject);
        }
    }

}
